﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Southridge.Data;
using Southridge.Business;
using System.Windows.Input;
using System.Windows.Data;
using System.ComponentModel;
using System.Windows;

namespace Southridge.View
{
    /// <summary>
    /// 
    /// </summary>
 
  public class MainViewModel : ViewModelBase 
    {
        ListingCollection _searchResultsCollection;        
        protected SearchFilter _filter = new SearchFilter() ;

        public MainViewModel() : base() { }

        public MainViewModel(IViewLogger logger) : base(logger) { } 

        
        public SearchFilter SearchFilter
        {
            get
            {
                return _filter; 
            } 
        } 


        public ListingCollection Results
        {
            get
            {
                if (_searchResultsCollection == null)
                {
#if SQLCE 
                    _searchResultsCollection  = new ListingCollection(
                            DBContext.SouthridgeDB.Listing.Include("Address").ToList<Listing>());

#else 
                    _searchResultsCollection = new ListingCollection( Database.Listings) ; 
#endif 
                } 
                return _searchResultsCollection; 
            }
            set
            {
                if (_searchResultsCollection != value)
                {
                    _searchResultsCollection = value;
                    OnPropertyChanged("Results");
                } 
               
            } 
        }

        bool _isMapViewActive = false; 

        public bool IsMapViewActive 
        { 
            get
            {
                return _isMapViewActive; 
            }
            set
            {
                if (_isMapViewActive != value)
                {
                    _isMapViewActive = value;
                    OnPropertyChanged("IsMapViewActive"); 
                } 
            } 
        }

        bool _isProfileActive = false;

        public bool IsProfileActive
        {
            get
            {
                return _isProfileActive;
            }
            set
            {
                if (_isProfileActive != value)
                {
                    _isProfileActive = value;
                    OnPropertyChanged("IsProfileActive");
                }
            }
        } 
       

        DataGridColumnsViewModel _dataGridColumnsView = new DataGridColumnsViewModel();
        public DataGridColumnsViewModel DataGridColumnsView
        {
            get
            {
                return _dataGridColumnsView;
            }
        }

        private Profile _currentProfile; 
        public Profile CurrentProfile
        {
            get
            {                
                return _currentProfile; 
            }
            set
            {
                if (_currentProfile != value)
                {
                    _currentProfile = value;
                    OnPropertyChanged("CurrentProfile"); 
                } 
            }
        }

        public FilterMetadata FilterMetadata
        {
            get
            {
                return FilterMetadata.Current;
            }
        }

        public MostRecentFiles MostRecentFiles
        {
            get
            {
                return MostRecentFiles.SingletonNotImplemented;     
            } 

        }

        
        public ICommand ShowColumnCommand
        {
            get
            {
                if (_showColumnCommand == null)
                {
                    _showColumnCommand = new DelegateCommand<object>(OnShowColumn, false);  
                }
                return _showColumnCommand; 
            }              
        } 

        public ICommand FilterChangedCommand
        {
            get
            {
                if ( _filterChangedCommand == null) 
                {
                    _filterChangedCommand = new DelegateCommand<object>(OnFilterChanged, false); 
 
                } 
                return _filterChangedCommand; 
            } 
        }

        public ICommand NotImplementedEnabledCommand
        {
            get
            {
                if (_notImplementedEnabledCommand == null)
                {
                    _notImplementedEnabledCommand = new DelegateCommand<object>(OnNotImplemented, false); 
                }
                return _notImplementedEnabledCommand; 
            } 
        }

        public ICommand SearchResultsCommand
        {
            get
            {
                if (_searchResultsCommand == null)
                {
                    _searchResultsCommand = new DelegateCommand<object>(OnSearchResults, false);
                }
                return _searchResultsCommand; 
            } 
        }

        protected void OnSearchResults(object o)
        { }



        public ICommand SearchSelectedCommand
        {
            get
            {
                if (_searchSelectedCommand == null)
                {
                    _searchSelectedCommand = new DelegateCommand<object>(OnSearchSelected, false);
                }
                return _searchSelectedCommand;
            }
        }

        protected void OnSearchSelected(object o)
        {
            ViewManager.Current.Transition(Views.Search);         
        } 

        public ICommand DetailsCommand 
        {
            get
            {
                if (_detailsCommand == null)
                {
                    _detailsCommand = new DelegateCommand<object>(OnDetails, false);
                }
                return _detailsCommand; 
            }
        }

        public ICommand OpenProfile
        {
            get
            {
                if (_openProfileCommand == null)
                {
                    _openProfileCommand = new DelegateCommand<object>(OnOpenProfile, false);
                }
                return _openProfileCommand;
            }
        }

        public ICommand NewProfile
        {
            get
            {
                if (_newProfileCommand == null)
                {
                    _newProfileCommand = new DelegateCommand<object>(OnNewProfile, false);
                }
                return _newProfileCommand;
            }
        }

        public ICommand SaveProfile
        {
            get
            {                 
                if (_saveProfileCommand == null)
                {
                    _saveProfileCommand = new DelegateCommand<object>(OnSaveProfile, OnCanSaveQuery , true); 
                }
                return _saveProfileCommand;
            }
        }


        public ICommand SkinToggleCommand
        {
            get
            {
                if (_skinToggleCommand == null)
                {
                    _skinToggleCommand = new DelegateCommand<object>(OnSkinToggle, false);
                }
                return _skinToggleCommand;
            }
        }

        protected bool IsLoaded = true;

        protected void OnSkinToggle( object t )
        {
            
            string []resources = new string []
            { 
                "pack://application:,,,/Southridge;component/Themes/NotStatic.xaml" ,                       
            }; 
 
            //Application.Current.Resources.MergedDictionaries.Clear(); 
            foreach ( string s in resources ) 
            {
                if (IsLoaded)
                {
                    foreach (ResourceDictionary rd in Application.Current.Resources.MergedDictionaries)
                    {
                        Uri uri = new Uri(s); 
                        if (rd.Source.AbsolutePath == uri.AbsolutePath )
                        {
                            Application.Current.Resources.MergedDictionaries.Remove(rd);
                            break; 
                        } 
                    } 
                }
                else
                {
                    ResourceDictionary rd = new ResourceDictionary();
                    rd.Source = new Uri(s, UriKind.Absolute);
                    Application.Current.Resources.MergedDictionaries.Add(rd);
                } 
            }
            IsLoaded = !IsLoaded; 

        } 

        protected bool OnCanSaveQuery(object t)
        {
            if (CurrentProfile != null)
            {
                 
                return CurrentProfile.IsDirty && CurrentProfile.IsValid;
            }
            return false; 
        }

        protected void OnOpenProfile(object o)
        {
            MostRecentFile mrf = o as MostRecentFile;
            


#if SQLCE 
            if (mrf != null)
            {
                if (mrf.Name.Length > 3 && mrf.Name.Substring(0, 4) == "Mark")
                    id = 2;  
                else
                    id = 1;                
            }
           Profile p = Profile.FindById(id);
#else
            Profile p = null;
            if (mrf != null && mrf.Name.Length > 3)
            {
                p = Database.Profiles.Where(a => a.FirstName.Substring(0,4) == mrf.Name.Substring(0, 4)).First<Profile>();
            }
            else
                p = new Profile(); 

            


#endif 
            CurrentProfile = p;               
            ViewManager.Current.Transition(Views.Profile, 
                new NewProfileViewModel(CurrentProfile)); 

        }


        
        protected void OnNewProfile(object o)
        {

#if SQLCE 
            this.CurrentProfile = Profile.CreateProfile(99); 
#else 
            this.CurrentProfile = new Profile(); 
#endif 
            
            ViewManager.Current.Transition(Views.Profile, new NewProfileViewModel(CurrentProfile)); 
             
        }

        protected void OnSaveProfile(object o)
        {
            if (CurrentProfile.SimpleSave())
            {
                ViewManager.Current.Transition(ViewManager.Current.BackView); 
            }
            else
            {
                _logger.LogError("Can not connect to database, try again");   
            } 

           
           // 
        } 

        protected void OnDetails(object o)
        { } 

        public ICommand OpenMap
        {
            get
            {
                if ( _openMapCommand== null)
                {
                    _openMapCommand = new DelegateCommand<object>(OnOpenMapExecuted, false);
                }
                return _openMapCommand;                  
            }
        }

        public ICommand ShowDetails 
        {
            get
            {
                if ( _showDetailsCommand == null)
                {
                    _showDetailsCommand = new DelegateCommand<object>(OnShowDetails, false);
                }
                return _showDetailsCommand;
            }
        }

        protected void OnShowDetails ( object param ) 
        {             
            ViewManager.Current.ShowWindow(
                Views.Details, true, new ListingDetailsViewModel ( param as Listing, this.CurrentProfile ) ); 
        } 

        protected void OnOpenMapExecuted(object o)
        {
            ViewManager.Current.Transition(Views.Map, this); 
             
        } 


        protected DelegateCommand<object> _filterChangedCommand ;
        protected DelegateCommand<object> _showColumnCommand ;
        protected DelegateCommand<object> _notImplementedEnabledCommand;
        protected DelegateCommand<object> _searchResultsCommand;
        protected DelegateCommand<object> _mapCommand;
        protected DelegateCommand<object> _detailsCommand;
        protected DelegateCommand<object> _openProfileCommand;
        protected DelegateCommand<object> _newProfileCommand;
        protected DelegateCommand<object> _saveProfileCommand;
        protected DelegateCommand<object> _showDetailsCommand;
        protected DelegateCommand<object> _openMapCommand;
        protected DelegateCommand<object> _closeMapCommand; 
        protected DelegateCommand<object> _searchSelectedCommand;
        protected DelegateCommand<object> _skinToggleCommand; 


        
        protected bool doOnce = false;

        protected void OnShowColumn (object param)
        {

        }

        protected void OnNotImplemented(object param)
        {
            // 
        }
        protected void OnFilterChanged(object param)
        {

            if (param != null && param is string)
            {
                string command = param as string;
                string[] commandparams = command.Split('-');

                double d = 0;

                if (commandparams.Length != 2)
                    return;

                if (!double.TryParse(commandparams[1], out d))
                    return;

                if (commandparams[0] == "Bathroom")
                {
                    SearchFilter.MinBathrooms = d;
                }
                else if (commandparams[0] == "Bedroom")
                {
                    SearchFilter.MinBedrooms = d;
                }
            }
            else
            {
                return;
            }
            ICollectionView view = CollectionViewSource.GetDefaultView(_searchResultsCollection);


            if (view != null)
            {
                IEditableCollectionView editable = view as IEditableCollectionView;
                if (editable != null)
                {
                    if (editable.IsAddingNew || editable.IsEditingItem)
                    {
                        LogMessage( Properties.Resources.CannotFilterWhileEditingError ); 
                        return; 
                    } 
                } 
                if (view.Filter == null)
                {
                    view.Filter = new Predicate<object>(OnCheckItem);
                }
                else if (view != null)
                    view.Refresh();
            }
        } 

        protected bool OnCheckItem(object o)
        {
            Listing li = o as Listing;
            bool match = true;
            if (li != null)
            {
                if (SearchFilter.MinBathrooms.HasValue)
                {
                    match &= (li.BathroomCount >= SearchFilter.MinBathrooms.Value);
                }
                if (SearchFilter.MinBedrooms.HasValue)
                    match &= (li.BedroomCount >= SearchFilter.MinBedrooms.Value);

            } 
            return match; 
        } 

        protected void OnApplyFilter(object sender, FilterEventArgs e)
        {
            Listing listing = e.Item as Listing;

            if (listing != null)
            {
                if (listing.BedroomCount == 3)
                    e.Accepted = true;

                else
                    e.Accepted = false;
            }
            else
                e.Accepted = false; 

        } 
    }
}
